<template>
  <div>
    全局自定义指令使用
    <input v-read="val" type="text" />
    <hr />
    <h1 v-edit="'我是局部自定义指令'">我是h1标签</h1>
    <hr />
    loading效果
    <!--4.循环数组,数组是获取的axios的数据-->
    <ul style="list-style: none">
      <li v-for="item in list" :key="item.id">
        <img :src="item.img" alt="" />{{ item.title }}
      </li>
    </ul>
    <!--6.创建遮罩层,使用自定义指令-->
    <!-- <div v-loading="list.length == 0" class="zindex"></div> -->
    <hr />
    <img
      v-errorImg="img"
      src="http://ajax-api.itheima.net/images/0322.webp"
      alt=""
    />
  </div>
</template>
<script>
import axios from 'axios';
import img from './assets/logo.png'

export default {
  name: '',
  data () {
    return {
      val: '123',
      list: [],
      img
    }
  },
  //局部自定义指令
  directives: {
    edit: {
      // inserted(dom元素, 目标对象,通过value可以获取传的值)
      inserted (ele, obj) {
        // console.log(ele, obj);
        // ele.innerHTML = obj.value
        // ele.style.backgroundColor = 'red'
        // ele.style.color = 'skyblue'
      }
    },
    loading: {
      // inserted(dom元素, 目标对象,通过value可以获取传的值)
      //5.当前dom加载完成后执行
      inserted (ele, obj) {
        console.log(ele, obj.value);
        ele.classList.add('zindex')
        ele.innerHTML = '正在加载中......'
      },
      //
      //update钩子函数,写在对应自定义事件里面,检测value变化
      //7.指令的dom元素更新了数据
      update (ele, obj) {
        console.log(ele, obj.value);
        setTimeout(() => {
          // ele.classList.remove('zindex')
          //移除遮罩效果
          ele.style.display = 'none'
        }, 2000)
      }
    },
    errorImg: {
      inserted (ele, obj) {
        //元素加载失败时就会触发
        ele.onerror = function () {
          console.log(ele);
          ele.src = obj.value
        }
      }
    }


  },
  created () {
    //3.data初始化之后调用函数发送请求
    this.senddata()
  },
  computed: {
  },
  methods: {
    //2.创建发送请求函数
    async senddata () {
      const res = await axios('http://hmajax.itheima.net/api/news')
      this.list = res.data.data
    }
  }
}
</script>
<style lang='less'  scoped>
.zindex {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(23, 18, 18, 0.7);
  text-align: center;
  line-height: 100vh;
  z-index: 2;
}
</style>
